<?php

class SiteService extends FServiceBase
{    
    /**
    * Get a Site model given its ID
    * 
    * @param int id Site ID
    * @return FServiceModel
    */
    public function get($params){
        $model = Site::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('CmsModule.Site','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        $model = $this->getModel($params['Site'],'Site');
        $this->result->processed('model', $model);
        
        $autoCreateWorkflow = $model->id == 0;
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('CmsModule.Site', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        elseif (! $model->save(false))
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('CmsModule.Site','Error while saving submitted data into database.'));
        elseif ($model->status && $model->default)
            $this->setDefault(array('id'=>$model->id));
        
        if ($model->hasErrors() == false) {
            //parse and create site urls
            $defaultUrl = '';
            $model->urls = explode("\n", $model->urls);
            if (is_array($model->urls) && count($model->urls)) {
                $model->urls = array_map('trim', $model->urls);
                $model->urls = array_filter($model->urls, 'strlen');
                $model->urls = array_unique($model->urls);
                if (count($model->urls))  {
                    foreach ($model->urls as $index => $url) {
                        $result = FSM::_run('Cms.SiteUrl.save', array('SiteUrl'=>array(
                            'site_id'=>$model->id,
                            'url'=>$url,
                            'status'=>SiteUrl::STATUS_ACTIVE,
                            'default'=>$index == 0,
                        )))->model;
                        if ($result->hasErrors()) {
                            Yii::log(CVarDumper::dumpAsString($result->getErrors()), CLogger::LEVEL_ERROR);
                        }
                        elseif ($index == 0)
                            $defaultUrl = $url;
                    }
                }
            }
            
            if ($autoCreateWorkflow) {                
                //create default workflow Live
                $url = empty($defaultUrl) ? '' : 'dev.'.$defaultUrl;
                $result = FSM::_run('Cms.Workflow.save', array(
                    'Workflow'=>array(
                        'site_id'=>$model->id,
                        'name'=>'Dev',
                        'url'=>$url,
                        'type'=>1,
                    ),
                    'auto'=>true
                ));
                //create default workflow Live
                $url = empty($defaultUrl) ? '' : 'live.'.$defaultUrl;
                $result = FSM::_run('Cms.Workflow.save', array(
                    'Workflow'=>array(
                        'site_id'=>$model->id,
                        'name'=>'Live',
                        'url'=>$url,
                        'type'=>2,
                    ),
                    'auto'=>true
                ));
                if ($result->hasErrors()) {
                    Yii::log(CVarDumper::dumpAsString($result->getErrors()), CLogger::LEVEL_ERROR);
                }
            }
            
            //create theme structure
            $basePath = Yii::app()->themeManager->basePath;
            $themeBasePath = $basePath.DIRECTORY_SEPARATOR.$model->name;
            if (!file_exists($themeBasePath))
            {
                @mkdir($themeBasePath);
                @chmod($themeBasePath, '0755');
            }
            $imagesBasePath = $themeBasePath.DIRECTORY_SEPARATOR.'images';
            if (!file_exists($imagesBasePath))
            {
                @mkdir($imagesBasePath);
                @chmod($imagesBasePath, '0755');
            }
            $scriptsBasePath = $themeBasePath.DIRECTORY_SEPARATOR.'scripts';
            if (!file_exists($scriptsBasePath))
            {
                @mkdir($scriptsBasePath);
                @chmod($scriptsBasePath, '0755');
            }
            $stylesBasePath = $themeBasePath.DIRECTORY_SEPARATOR.'styles';
            if (!file_exists($stylesBasePath))
            {
                @mkdir($stylesBasePath);
                @chmod($stylesBasePath, '0755');
            }
            $viewsBasePath = $themeBasePath.DIRECTORY_SEPARATOR.'views';
            if (!file_exists($viewsBasePath))
            {
                @mkdir($viewsBasePath);
                @chmod($viewsBasePath, '0755');
            }
            $layoutsBasePath = $viewsBasePath.DIRECTORY_SEPARATOR.'layouts';
            if (!file_exists($layoutsBasePath))
            {
                @mkdir($layoutsBasePath);
                @chmod($layoutsBasePath, '0755');
            }
            $systemBasePath = $viewsBasePath.DIRECTORY_SEPARATOR.'system';
            if (!file_exists($systemBasePath))
            {
                @mkdir($systemBasePath);
                @chmod($systemBasePath, '0755');
            }
        }
        
        return $this->result;
    }
    /**
    * List all locale ID of supported languages
    * 
    * @param mixed $params
    * @return FServiceModel
    */
    public function getSupportedLanguages($params = array()){
        // todo: list all locale ID of supported languages
        Yii::import('Core.models.Language');
        $localeID=array();
        //List all model
        $languages=Language::model()->findAll('status=true');
        if (is_null($languages))
            return $this->result->fail(5,Yii::t('Cms.Site','Language is not found.'));    
            
         foreach($languages as $language){
             $localeID[]=$language->locale_id;
         }   
        //$this->result->processed('name', $user->username);
        
        if (count($localeID)>0)
            $this->result->processed('localeID', $localeID);
        else
            $this->result->processed('localeID', array());
            
        //if (isset($this->result->_data['model']))
//            unset($this->result->_data['model']);
            
        return $this->result;
    }
    
    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('CmsModule.Site','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = Site::model()->findByPk($id);
            try {
                if ($model->delete()) {
                    FSM::_run('Cms.siteUrl.deleteBySite', array('site_id'=>$id));
                    FSM::_run('Cms.Workflow.deleteBySite', array('site_id'=>$id));
                    FSM::_run('Cms.page.deleteBySite', array('site_id'=>$id));
                    //remove theme folder
                    $basePath = Yii::app()->themeManager->basePath;
                    $themeBasePath = $basePath.DIRECTORY_SEPARATOR.$model->name;
                    $this->rrmdir($themeBasePath);
                }
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
    
    protected function rrmdir($dir) {
        if (is_dir($dir))
        {
            $objects = scandir($dir);
            foreach ($objects as $object)
            {
                if ($object != "." && $object != "..")
                {
                    if (filetype($dir."/".$object) == "dir")
                        $this->rrmdir($dir."/".$object);
                    else
                        @unlink($dir."/".$object);
                }
            }
            reset($objects);
            @rmdir($dir);
        }
    } 
    
    public function changeStatus($params) {
        $ids = $this->getParam($params, 'ids', array());
        $value = $this->getParam($params, 'value', false);
        
        if (count($ids) <= 0)
            return $this->result;
        
        $criteria = new CDbCriteria();
        $criteria->addInCondition('id', $ids);
        $models = Site::model()->findAll($criteria);
        foreach ($models as $model) {
            /**
            * @var Site $model
            */
            $model->status = (boolean) $value;
            if (! $model->save(false, array('status')))
                $this->result->fail(ERROR_HANDLING_DB, Yii::t('CmsModule.Site','Error while saving submitted data into database.'));
        }
        
        return $this->result;
    }
    
    public function setDefault($params)
    {
        $id = $this->getParam($params, 'id', false);
        if ($id) {
            $model = Site::model()->findByPk($id);
            if (is_object($model) && $model->status) {
                Site::model()->updateAll(array('default'=>false));
                Site::model()->updateByPk($id, array('default'=>true));
            }
        }
        return $this->result;
    }
    
    public function getList()
    {
        $criteria = new CDbCriteria();
        $criteria->compare('status', true);
        $criteria->order = 'name';
        $models = Site::model()->findAll($criteria);
        $this->result->processed('models', $models);
        return $this->result;
    }
    
    public function getDefault($params)
    {
        $id = Yii::app()->session->get('global_site_id',0);
        if (Site::model()->count('id = :id', array(':id' => $id)) <= 0)
        {
            $model = Site::model()->findByAttributes(array('default'=>true));
            $id = 0;
            if (is_object($model))
                $id = $model->id;
            Yii::app()->session['global_site_id'] = $id;
        }
        $this->result->processed('id', $id);
        return $this->result;
    }
    
    public function setCurrent($params)
    {
        $siteId = $this->getParam($params, 'site_id', 0);
        
        if ($siteId)
            Yii::app()->session['global_site_id'] = $siteId;
        return $this->result;
    }
    
    public function lookup($params)
    {
        $model = null;
        $workflow = FSM::_run('Cms.workflow.lookup')->model;
        if (is_object($workflow))
            $model = Site::model()->findByPk($workflow->site_id);
        
        $this->result->processed('model', $model);
        return $this->result;
    }
    /**
    * Get the master layout used when render view
    * by default, the master layout is the site name
    * @param int $id Site ID
    * @return string $layout
    */
    public function getMasterLayout($params) {
        $layout = null;
        $workflow = Yii::app()->cmsManager->workflow;
        if (is_array($workflow) && array_key_exists('id', $workflow))
        {
            $model = Workflow::model()->findByPk($workflow['id']);
            if (is_object($model))
            {
                $templateContent = TemplateContent::model()->findByPk($model->master_layout_revision);
                if (is_object($templateContent))
                {
                    $layout = '//layouts/'.$templateContent->getView();
                }
            }
        }
            
        return $this->result->processed('layout', $layout);;
    }
}
